import React, { useState, useEffect } from 'react';

const BaiduMapAutocomplete = () => {
    const [suggestions, setSuggestions] = useState([]);
    let ac = null;

    useEffect(() => {
        ac = new window.BMap.Autocomplete({
            input: "searchBox",
            location: new window.BMap.Map("map")
        });

        ac.addEventListener("onconfirm", (e) => {
            const item = e.item;
            const myValue = item.value;
            const local = new window.BMap.LocalSearch(new window.BMap.Map("map"), {
                onSearchComplete: (results) => {
                    if (local.getStatus() === window.BMAP_STATUS_SUCCESS) {
                        const poi = results.getPoi(0);
                        console.log(poi.title, poi.point);
                    }
                }
            });
            local.search(myValue);
        });

        return () => {
            
        };
    }, []);

    const handleSelectSuggestion = (value) => {
        document.getElementById("searchBox").value = value;
        setSuggestions([]);
    };

    return (
        <div>
            <input type="text" id="searchBox" placeholder="请输入关键字" />
            <ul>
                {suggestions.map((suggestion, index) => (
                    <li key={index} onClick={() => handleSelectSuggestion(suggestion)}>
                        {suggestion}
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default BaiduMapAutocomplete;